package com.xiezc.controller;

import com.xiaoleilu.hutool.cache.impl.TimedCache;
import com.xiaoleilu.hutool.lang.Assert;
import com.xiezc.dao.FileInfoRepository;
import com.xiezc.dto.ExcepEnum;
import com.xiezc.entity.FileInfo;
import com.xiezc.dto.RespData;
import com.xiezc.entity.User;
import com.xiezc.util.Md5Util;
import com.xiezc.util.XUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.stream.Collectors;

/**
 * 上传文件的相关类
 * Created by wb-xzc291800 on 2017/6/15.
 */
@RestController
@RequestMapping("upload")
public class UploadAction {
    @Resource
    private TimedCache timedCache;
    @Value("${filePath}")
    private String filePath;
    @Resource
    private FileInfoRepository fileInfoRepository;

    /**
     * 上传文件
     *
     * @return
     */
    @RequestMapping(value = "/uploadFile")
    public Callable<RespData> upFile(HttpServletRequest request, final @RequestParam MultipartFile file) {
        return () -> {

            Assert.notNull(file, "请上传文件");
            User user = (User) request.getAttribute("user");

            if (Objects.isNull(user)) {
                return new RespData(ExcepEnum.NotLogin);
            }

            List<FileInfo> fileInfoList = (List<FileInfo>) timedCache.get(XUtil.WAIT_UP_FILE);

            if (Objects.isNull(fileInfoList) || CollectionUtils.isEmpty(fileInfoList)) {
                return new RespData(ExcepEnum.UploadOutTime);
            }

            String fileMd5 = Md5Util.getBase64Md5(file.getInputStream());

            List<FileInfo> fileInfos = fileInfoList
                    .parallelStream()
                    .filter(fileInfo -> Objects.equals(fileMd5, fileInfo.getFileMd5()))
                    .collect(Collectors.toList());

            if (!fileInfos.isEmpty()) {
                Path path = Paths.get(filePath + user.getUserName());
                if (!Files.exists(path) || !Files.isDirectory(path)) {
                    path.toFile().mkdirs();
                }
                Path path1 = Paths.get(filePath + user.getUserName() + File.separator + fileMd5);
                Files.deleteIfExists(path1);
                Files.createFile(path1);

                file.transferTo(path1.toFile());

                //移除缓存
                fileInfoList.removeAll(fileInfos);
                if (!fileInfoList.isEmpty()) {
                    timedCache.put(XUtil.WAIT_UP_FILE, fileInfoList);
                } else {
                    timedCache.remove(XUtil.WAIT_UP_FILE);
                }
                //存入数据库
                fileInfos.forEach(f -> {
                    fileInfoRepository.save(f);
                });

                return new RespData();
            } else {
                return new RespData(ExcepEnum.UPRightFILE);
            }
        };
    }

}
